package com.filter;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.util.JWTTokenUtil;
import com.util.JsonUtil;

import javax.security.sasl.AuthenticationException;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;


//@WebFilter("/*")   //  /* 表示访问MyWeb2项目的任意资源都会执行该过滤器中的代码
@WebFilter("*.do")   //表示url中有.do后缀就可以访问该过滤器,一般我们会在需求登录验证的Servlet url地址的后面加上.do


/**
 *   /DDBookServlet.do
 * /UserServlet
 */
//@WebFilter("/manager/*") //表示url路径中 包含/manager/的字符串就是执行该过滤器
public class LoginValidateFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    /**
     *     ServletRequest servletRequest  客户端的请求信息
     *    ServletResponse servletResponse 客户端的响应信息对象
     *    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
     *
     *
     *    FilterChain filterChain 代表一个过滤器链,调用该对象的doFilter方法才可以将请求给到下一个过滤器，或目标Servlet
     */
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
      //  servletRequest.getClass().getName()
        HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;


        System.out.println("LoginValidateFilter doFilter方法被执行");
        JsonUtil jsonUtil = new JsonUtil();
        GsonBuilder gsonBuilder = new GsonBuilder();
        Gson gson =  gsonBuilder.create();

        JWTTokenUtil jwtTokenUtil = new JWTTokenUtil();
        servletResponse.setContentType("text/html;charset=utf-8");
        PrintWriter out = servletResponse.getWriter();
        try{


        String loginUserInfo =   jwtTokenUtil.getDecodeToken(httpServletRequest);//用JWTToken解密客户传递过的参数access_token
        servletResponse.setContentType("text/html;charset=utf-8");



            if (loginUserInfo==null){//表示用户未登录过
                jsonUtil.setCode(999);
                jsonUtil.setMsg("您还未登录，请先登录");
                //提示用户请先登录
                //在过滤器直接返回结果给客户端。。
                out.print(gson.toJson(jsonUtil));

            }else{
                System.out.println("当前的登录用户名为:"+loginUserInfo);



                filterChain.doFilter(servletRequest,servletResponse);//访问下一下过滤器或目标Servlet
            }
        }catch (AuthenticationException exception){
            jsonUtil.setCode(999);
            jsonUtil.setMsg("登录超时，请重新登录");
            //提示用户请先登录
            //在过滤器直接返回结果给客户端。。
            out.print(gson.toJson(jsonUtil));
        }


    }

    @Override
    public void destroy() {

    }
}
